package com.kgc.onlineLife.controller;

import com.kgc.onlineLife.bean.*;
import com.kgc.onlineLife.service.CategoryService;
import com.kgc.onlineLife.service.ForeService;
import com.kgc.onlineLife.service.ProductsService;
import com.kgc.onlineLife.service.ReviewService;
import com.kgc.onlineLife.service.*;
import com.kgc.onlineLife.util.KeyWordFilter;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created On : 2022/4/15.
 * <p>
 * Author     : 张冲
 * <p>
 * Description: 前台请求
 */
@Controller
@RequestMapping("/fore")
public class ForeController {

    @Autowired
    private ForeService foreService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductsService productsService;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    private OrderService orderService;

    /**
     * 前台首页
     * @param
     * @return
     */
    @RequestMapping("/foreIndex")
    public String index(HttpSession session, Map<String,Object> map){

        //传入4个分类
        List<Category> categories = foreService.listToFour();
        //查询分类详情
        List<Category> categoryDetails = categoryService.categoryList();
        //查商品信息
        //Product product = productsService.getProduct(id);
        //给每个分类设置商品
        for (Category c:categories){
            List<Product> products = productsService.getProductsByCid(c.getId());
            //如果分类下的商品超过5个，则只显示5个给前端
            if(products.size()>5){
                List<Product> products1 = new ArrayList<>();
                for(int i=0;i<=4;i++){
                    products1.add(products.get(i));
                }
                c.setProducts(products1);
            }else{
                c.setProducts(products);
            }
        }
        /**
         * 展示分类
         */
        map.put("categories",categories);
        /**
         * 全部分类
         */
        map.put("categoriesAll",categoryDetails);
       // map.put("product",product);
        session.setAttribute("categoriesAll",categoryDetails); //保存在session  使其他页面也能获取到分类列表 而不用每次都去查询
        return "Fore/forepage/index2";
    }

    /**
     * 商品详情跳转
     * @param id
     * @param
     * @return
     */
    @RequestMapping("/foreDetailUI")
    public String detailUI(@RequestParam("id")int id, Map<String,Object> map,HttpSession session){
        Product product = productsService.getProductsById(id);
        if(product==null){
            return "Fore/forepage/noPro";
        }
        //查商家名
        User user = productsService.getUserByBid(product.getBid());
        //查分类
        Category category = productsService.getCategoryByCid(product.getCid());
        product.setCategory(category);
        product.setUser(user);

        //随机推荐5个菜品
        List<Product> fivePro = foreService.randProductFive();

        map.put("product",product);
        map.put("fivePro",fivePro);

        List<Review> list = reviewService.getReviewListByPid(id);

        map.put("reviews",list);
        map.put("rs",list.size());

        System.out.println(list);

        /**
         * 添加足迹
         */
        Customer customer =(Customer)  session.getAttribute("cst");
        foreService.insertIntofootPrint(customer.getId(),id);

        return "Fore/forepage/proDetail";
    }

    /**
     * 搜索商品
     * @param
     * @param
     * @return
     */
    @RequestMapping("/foreNameLike")
    public String foreNameLike(HttpServletRequest request, Map<String,Object> map){
        String searchName = request.getParameter("pName")==null?"": request.getParameter("pName");

        //商品结果集
        List<Product> productList = productsService.selectProductDetailBySearchName(searchName);

        //总条数
        int total = productsService.selectTotalBySearchName(searchName);
        System.out.println("**************************"+total+"**************************");

        map.put("products",productList);
        map.put("total",total);



        return "Fore/forepage/proSearch";
    }

    /**
     * 显示分类下的商品
     */
    @RequestMapping("/foreFindCategory")
    public String foreFindCategory(@RequestParam("id") Integer cid,Map<String,Object> map){
        //查分类下所有商品
        List<Product> products = productsService.getProductsByCid(cid);
        //根据分类编号查分类
        Category category = categoryService.selectCategoryByCid(cid);
        //查询分类条数
        int total = productsService.selectCategoryTotalByCid(cid);

        map.put("pro",products);
        map.put("category",category);
        map.put("total",total);

        return "Fore/forepage/proCategorySearch";
    }

    /**
    * @author: HarryXzy
    * @date: 2022/4/20 7:27 下午
    * @return:
    * @description: 加入购物车时判断是否登陆
    **/
    @RequestMapping("/foreIsLogin")
    @ResponseBody
    public String isLogin(HttpSession session){
        Customer cst = (Customer) session.getAttribute("cst");
        return cst==null?"false":"true";
    }


    /**
    * @author: HarryXzy
    * @date: 2022/4/21 11:26 上午
    * @return:
    * @description: 订单详情中添加商品评价
    **/
    @ResponseBody
    @RequestMapping("/foreAddReview")
    public String foreAddReview(@Param("pid") Integer pid,
                                @Param("content")String content,
                                HttpSession session){
        Customer customer =(Customer) session.getAttribute("cst");
        if(customer==null){
            return "请先登陆";
        }else{
            long time = new Date().getTime();
            Date date1 = new Date(time);
            Review review = new Review();
            review.setPid(pid);

            //敏感词过滤
            KeyWordFilter.initPattern();
            String str = content;
            System.out.println("被检测字符串长度:"+str.length());
            str = KeyWordFilter.doFilter(str);
            System.out.println("替换后的字符串为:\n"+str);


            review.setContent(str);
            review.setCstid(customer.getId());
            review.setCreatetime(date1);
            reviewService.addReview(review);
            System.out.println(date1);
            return "success";
        }
    }

    /**
     * ajax判断加购物车
     * @param session
     * @return
     */
    @RequestMapping("/foretoAddCart")
    @ResponseBody
    public String addCart( HttpSession session) {
        Customer customer =(Customer) session.getAttribute("cst");
        if(customer==null){
            return "false";
        }
        return "success";
    }

    /**
     * 添加购物车
     */
    @RequestMapping("/foreAddCart")
    @ResponseBody
    public String addCart(OrderItem orderItem, HttpSession session){
        // 判断用户登录
        Customer customer = (Customer) session.getAttribute("cst");
        if (customer == null){
            return "redirect:/fore/foreLoginUI";
        }
        // 根据用户id显示用户添加购物车内容
        List<OrderItem> ois = orderItemService.listByCustomer(customer.getId());
        // 判断购物车内是否有相同商品，如果有，只添加数量
        for (OrderItem oi : ois){
            if (oi.getProduct().getId().equals(orderItem.getPid())){
                OrderItem orderItem1 = new OrderItem();
                orderItem1.setId(oi.getId());
                orderItem1.setNumber(oi.getNumber()+orderItem.getNumber());
                orderItemService.update(orderItem1);
                return "success";
            }

        }
        // 如果查询没有相同商品，执行添加操作
        orderItem.setCstid(customer.getId());
        if(orderItemService.insert(orderItem)){
            System.out.println("成功");
        } else {
            System.out.println("失败");
        }
        return "success";
    }

    /**
     * 查看购物车
     */
    @RequestMapping("/forecart")
    public String cart(Model model,HttpSession session){
        // 判断用户登录
        Customer customer =(Customer)  session.getAttribute("cst");
        if (customer == null){
            return "redirect:/fore/foreLoginUI";
        }
        // 根据用户id显示购物车
        List<OrderItem> ois = orderItemService.listByCustomer(customer.getId());

        // 如果购物车没有商品，跳转无商品提示页面
        if(ois==null || ois.size()==0){
            return "Fore/forepage/cart_noPro";
        }

        int totalProductNumber = 0;
        for (OrderItem oi:ois){
            totalProductNumber =totalProductNumber + oi.getNumber();
        }
        model.addAttribute("orderitems", ois);
        model.addAttribute("size", totalProductNumber);

        return "/Fore/forepage/foreCart";
    }

    /**
     * 删除购物车订单
     */
    @RequestMapping("/foreDelOrderItem/{id}")
    public String foreDelOrderItem(@PathVariable("id") int id){
        orderItemService.delete(id);
        return "redirect:/fore/forecart";
    }

    /**
     * 批量删除购物车
     */
    @RequestMapping("/foreBatchDelOrderItem")
    public String foreBatchDelOrderItem(@RequestParam("oiid") String[] oiid){
        System.out.println(Arrays.toString(oiid));
        for (String oiids : oiid){
            orderItemService.delete(Integer.valueOf(oiids));
        }
        return "redirect:/fore/forecart";
    }




    /**
    * @author: HarryXzy
    * @date: 2022/4/18 4:07 下午
    * @return:
    * @description: 我的订单
    **/
    @RequestMapping("/forebought")
    public String forebought(Model model, HttpSession session){
        Customer customer = (Customer) session.getAttribute("cst");
        //没有登陆去登陆
        if(customer==null){
            return "redirect:/fore/foreLoginUI";
        }else{
            List<Order> os= orderService.myOrders(customer.getId());
            //给每个订单的订单项设置属性值，orderitems、total等
            orderService.fill(os);
            model.addAttribute("os", os);
            return "Fore/forepage/foreBought";
        }

    }

/**
* @author: HarryXzy
* @date: 2022/4/26 9:42 下午
* @return:
* @description: 再次购买
**/
    @ResponseBody
    @RequestMapping("/foreBuyAgain")
    public String foreBuyAgain(@RequestParam("code")String code, Model model, HttpSession session){
    int i = orderService.selectOrderByCode(code);
    List<OrderItem> orderItems =orderItemService.listByOid(i);
    System.out.println(orderItems);
    Customer customer = (Customer) session.getAttribute("cst");
    for(OrderItem orderItem:orderItems){
        orderItem.setOid(null);
        orderItem.setCstid(customer.getId());
        orderItemService.insert(orderItem);
    }

    return "success";
    }




    /**
     * 下单按钮
     * @param session
     * @param oiid
     * @param map
     * @return
     */
    @RequestMapping("/foreBuy")
    public String foreBuy(HttpSession session, @RequestParam("oiid") String[] oiid, Map<String,Object> map){
        session.setAttribute("oiids", oiid);
        double total = 0;
        Integer number = 0;
        List<OrderItem> orderItems = new ArrayList<>();
        for (String strid : oiid){
            OrderItem orderItem = orderItemService.listById(Integer.parseInt(strid));
            orderItems.add(orderItem);
            total += orderItem.getProduct().getPrice() * orderItem.getNumber();
            number += orderItem.getNumber();
        }
        map.put("ois",orderItems);
        map.put("total",total);
        map.put("number",number);

        return "Fore/forepage/foreBuy";
    }

    /**
     * @author : 98730
     * @date   : 2022/4/19
     * @param  : [javax.servlet.http.HttpSession, java.lang.String]
     * @return : java.lang.String
     * @description : 提交订单
     */
    @RequestMapping(value = "/foreCreateOrder", params = {"address", "price", "name", "phone"})
    public String createOrder(HttpSession session,String address,String price,String name,String phone){
        Order order = new Order();
        Customer customer = (Customer) session.getAttribute("cst");
        String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000);

        order.setCode(orderCode);
        order.setAddress(address);
        order.setCstid(customer.getId());
        order.setStatus(1);

        orderService.add(order);

        // 打印传过来的价格总数
        session.setAttribute("price", price);
        session.setAttribute("aliName", name);
        session.setAttribute("aliphone", phone);

        return "redirect:/Alipay/to_alipay.do?orderCode=" + orderCode;
    }

    /**
     * @author : 98730
     * @date   : 2022/4/19
     * @param  : [int, double, java.util.Map<java.lang.String,java.lang.Object>]
     * @return : java.lang.String
     * @description : 跳转支付成功页面
     */
    @RequestMapping("/forePayed")
    public String payed(int oid, double total, Map<String,Object> map,HttpSession session){
        Order order = (Order) orderService.myOrders(oid);

        orderService.update(order);
        map.put("total",total);
        // 添加oid
        return "Fore/forepage/forePayed";
    }

    /**
     * 收藏
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("/addCollection")
    public String Collection(@RequestParam("pid") Integer pid, HttpSession session,Map<String,Object> map){
        Customer customer =(Customer)  session.getAttribute("cst");

        foreService.insertIntoCollection(pid,customer.getId());

        return "redirect:/fore/foreIndex";
    }

    /**
     * 取消收藏
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("/deleteCollection")
    public String deleteCollection(@RequestParam("pid") Integer pid, HttpSession session,Map<String,Object> map){
        Customer customer =(Customer)  session.getAttribute("cst");


        //查询收藏商品编号
        List<Integer> collectId = foreService.selectCollectionId(customer.getId(),pid);

        //删除收藏商品
        foreService.deleteCollection(collectId);


        return "redirect:/fore/collection";
    }

    /**
     * 查寻收藏
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("/collection")
    public String collection(HttpSession session,Map<String,Object> map){
        Customer customer =(Customer)  session.getAttribute("cst");

        //查询收藏商品列表
        List<Product> list = foreService.selectCollection(customer.getId());
        //查询收藏列表条数
        Integer total = foreService.selectTotalCollection(customer.getId());

        map.put("total",total);
        map.put("products",list);
        return  "Fore/forepage/foreCollection";
    }


    /**
     * 查寻足迹
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("/zuji")
    public String zuji(HttpSession session,Map<String,Object> map){
        Customer customer =(Customer)  session.getAttribute("cst");

        //查询足迹商品列表
        List<Product> list = foreService.selectFootPrint(customer.getId());
        //查询足迹列表条数
        Integer total = foreService.selectTotalFootPrint(customer.getId());

        map.put("total",total);
        map.put("products",list);
        return  "Fore/forepage/footPrint";
    }



}


